import { defineStore } from 'pinia'
import { ref, reactive, computed } from 'vue'

// 流程变量定义
export interface ProcessVariable {
  name: string
  type: 'string' | 'double' | 'long' | 'boolean' | 'date'
  label: string
  defaultValue?: any
}

// 节点基础接口
export interface BaseNode {
  id: string
  name: string
  position: { x: number; y: number }
}

// 开始节点
export interface StartNode extends BaseNode {
  type: 'START'
}

// 审批节点
export interface ApprovalNode extends BaseNode {
  type: 'APPROVAL'
  assigneeType: 'FIXED' | 'ROLE' | 'EXPRESSION'
  assignee: string
  formKey?: string
  allowReject?: boolean
}

// 条件分支节点
export interface ConditionalBranchNode extends BaseNode {
  type: 'CONDITIONAL_BRANCH'
  defaultFlow?: string
}

// 结束节点
export interface EndNode extends BaseNode {
  type: 'END'
}

// 联合节点类型
export type WorkflowNode = StartNode | ApprovalNode | ConditionalBranchNode | EndNode

// 连线定义
export interface WorkflowFlow {
  id: string
  name?: string
  from: string
  to: string
  condition?: string | null
}

// 完整的流程定义
export interface ProcessDefinition {
  id?: string
  name: string
  key: string
  description?: string
  variables?: ProcessVariable[]
  nodes: WorkflowNode[]
  flows: WorkflowFlow[]
}

export const useWorkflowDesignerStore = defineStore('workflowDesigner', () => {
  // 当前流程定义
  const currentProcess = reactive<ProcessDefinition>({
    name: '新建流程',
    key: '',
    description: '',
    variables: [],
    nodes: [],
    flows: []

  // 选中状态
  const selectedNodeId = ref<string>('')
  const selectedFlowId = ref<string>('')

  // 历史记录
  const history = reactive({
    undoStack: [] as string[],
    redoStack: [] as string[],
    maxHistorySize: 50

  // 计算属性
  const selectedNode = computed(() => {
    return currentProcess.nodes.find(n => n.id === selectedNodeId.value) || null

  const selectedFlow = computed(() => {
    return currentProcess.flows.find(f => f.id === selectedFlowId.value) || null

  // 添加节点
  const addNode = (type: WorkflowNode['type'], position: { x: number; y: number }) => {
    const nodeId = `${type.toLowerCase()}_${Date.now()}`
    
    let newNode: WorkflowNode
    
    switch (type) {
      case 'START':
        newNode = {
          id: nodeId,
          name: '开始',
          type: 'START',
          position
        }
        break
      case 'APPROVAL':
        newNode = {
          id: nodeId,
          name: '审批节点',
          type: 'APPROVAL',
          assigneeType: 'FIXED',
          assignee: '',
          formKey: '',
          allowReject: true,
          position
        }
        break
      case 'CONDITIONAL_BRANCH':
        newNode = {
          id: nodeId,
          name: '条件分支',
          type: 'CONDITIONAL_BRANCH',
          defaultFlow: '',
          position
        }
        break
      case 'END':
        newNode = {
          id: nodeId,
          name: '结束',
          type: 'END',
          position
        }
        break
      default:
        throw new Error(`未知节点类型: ${type}`)
    }

    currentProcess.nodes.push(newNode)
    selectedNodeId.value = newNode.id
    saveToHistory()
    
    return newNode
  }

  // 删除节点
  const deleteNode = (nodeId: string) => {
    const nodeIndex = currentProcess.nodes.findIndex(n => n.id === nodeId)
    if (nodeIndex > -1) {
      currentProcess.nodes.splice(nodeIndex, 1)
      // 删除相关连接
      currentProcess.flows = currentProcess.flows.filter(
        f => f.from !== nodeId && f.to !== nodeId

      if (selectedNodeId.value === nodeId) {
        selectedNodeId.value = ''
      }
      saveToHistory()
    }
  }

  // 更新节点
  const updateNode = (nodeId: string, updates: Partial<WorkflowNode>) => {
    const node = currentProcess.nodes.find(n => n.id === nodeId)
    if (node) {
      Object.assign(node, updates)
      saveToHistory()
    }
  }

  // 添加连接
  const addFlow = (from: string, to: string, condition?: string | null) => {
    // 检查是否已存在连接
    const existingFlow = currentProcess.flows.find(
      f => f.from === from && f.to === to

    if (existingFlow) {
      return existingFlow
    }

    const newFlow: WorkflowFlow = {
      id: `flow_${Date.now()}`,
      from,
      to,
      condition: condition || null,
      name: ''
    }

    currentProcess.flows.push(newFlow)
    saveToHistory()
    
    return newFlow
  }

  // 删除连接
  const deleteFlow = (flowId: string) => {
    const index = currentProcess.flows.findIndex(f => f.id === flowId)
    if (index > -1) {
      currentProcess.flows.splice(index, 1)
      if (selectedFlowId.value === flowId) {
        selectedFlowId.value = ''
      }
      saveToHistory()
    }
  }

  // 选中节点
  const selectNode = (nodeId: string) => {
    selectedNodeId.value = nodeId
    selectedFlowId.value = ''
  }

  // 选中连接
  const selectFlow = (flowId: string) => {
    selectedFlowId.value = flowId
    selectedNodeId.value = ''
  }

  // 清空选择
  const clearSelection = () => {
    selectedNodeId.value = ''
    selectedFlowId.value = ''
  }

  // 保存到历史记录
  const saveToHistory = () => {
    const currentState = JSON.stringify({
      process: currentProcess,
      selectedNodeId: selectedNodeId.value,
      selectedFlowId: selectedFlowId.value

    history.undoStack.push(currentState)
    
    // 限制历史记录大小
    if (history.undoStack.length > history.maxHistorySize) {
      history.undoStack.shift()
    }
    
    // 清空重做栈
    history.redoStack = []
  }

  // 撤销
  const undo = () => {
    if (history.undoStack.length > 0) {
      // 保存当前状态到重做栈
      const currentState = JSON.stringify({
        workflow: currentWorkflow,
        selectedNodeId: selectedNodeId.value,
        selectedConnection: selectedConnection.value

      history.redoStack.push(currentState)
      
      // 恢复上一个状态
      const prevState = history.undoStack.pop()
      if (prevState) {
        const state = JSON.parse(prevState)
        Object.assign(currentWorkflow, state.workflow)
        selectedNodeId.value = state.selectedNodeId
        selectedConnection.value = state.selectedConnection
      }
    }
  }

  // 重做
  const redo = () => {
    if (history.redoStack.length > 0) {
      // 保存当前状态到撤销栈
      const currentState = JSON.stringify({
        workflow: currentWorkflow,
        selectedNodeId: selectedNodeId.value,
        selectedConnection: selectedConnection.value

      history.undoStack.push(currentState)
      
      // 恢复重做状态
      const nextState = history.redoStack.pop()
      if (nextState) {
        const state = JSON.parse(nextState)
        Object.assign(currentWorkflow, state.workflow)
        selectedNodeId.value = state.selectedNodeId
        selectedConnection.value = state.selectedConnection
      }
    }
  }

  // 清空工作流
  const clearWorkflow = () => {
    currentWorkflow.nodes = []
    currentWorkflow.connections = []
    selectedNodeId.value = ''
    selectedConnection.value = null
    saveToHistory()
  }

  // 初始化工作流
  const initWorkflow = () => {
    currentWorkflow.id = `workflow_${Date.now()}`
    currentWorkflow.name = '新建工作流'
    currentWorkflow.description = ''
    currentWorkflow.nodes = []
    currentWorkflow.connections = []
    currentWorkflow.version = 1
    currentWorkflow.status = 'draft'
    selectedNodeId.value = ''
    selectedConnection.value = null
    saveToHistory()
  }

  // 导入工作流
  const importWorkflow = (workflowData: WorkflowData) => {
    Object.assign(currentWorkflow, workflowData)
    selectedNodeId.value = ''
    selectedConnection.value = null
    saveToHistory()
  }

  // 导出工作流
  const exportWorkflow = (): WorkflowData => {
    return JSON.parse(JSON.stringify(currentWorkflow))
  }

  // 验证工作流
  const validateWorkflow = () => {
    const errors: string[] = []
    
    // 检查是否有开始节点
    const startNodes = currentWorkflow.nodes.filter(n => n.type === 'start')
    if (startNodes.length === 0) {
      errors.push('工作流必须包含一个开始节点')
    } else if (startNodes.length > 1) {
      errors.push('工作流只能包含一个开始节点')
    }
    
    // 检查是否有结束节点
    const endNodes = currentWorkflow.nodes.filter(n => n.type === 'end')
    if (endNodes.length === 0) {
      errors.push('工作流必须包含至少一个结束节点')
    }
    
    // 检查节点连接
    currentWorkflow.nodes.forEach(node => {
      if (node.type !== 'end') {
        const outgoingConnections = currentWorkflow.connections.filter(c => c.from === node.id)
        if (outgoingConnections.length === 0) {
          errors.push(`节点"${node.name}"没有输出连接`)
        }
      }
      
      if (node.type !== 'start') {
        const incomingConnections = currentWorkflow.connections.filter(c => c.to === node.id)
        if (incomingConnections.length === 0) {
          errors.push(`节点"${node.name}"没有输入连接`)
        }
      }

    return errors
  }

  return {
    // 状态
    currentWorkflow,
    selectedNodeId,
    selectedConnection,
    history,
    
    // 方法
    addNode,
    deleteNode,
    updateNode,
    addConnection,
    deleteConnection,
    selectNode,
    selectConnection,
    clearSelection,
    saveToHistory,
    undo,
    redo,
    clearWorkflow,
    initWorkflow,
    importWorkflow,
    exportWorkflow,
    validateWorkflow
  }
